package dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

import dao.OrderItemDao;
import domain.Order;
import domain.OrderItem;
import domain.Product;
import domain.User;
import util.DataSourceUtils;

public class OrderItemDaoImpl implements OrderItemDao {

	@Override
	public List<OrderItem> findOrderItemByOrder(Order order) throws SQLException {
		String sql = "select orderitem.*,products.* from orderitem inner join products on orderitem.product_id=products.id where order_id=?";
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		return runner.query(sql, new ResultSetHandler<List<OrderItem>> () {

			@Override
			public List<OrderItem> handle(ResultSet rs) throws SQLException {
				List<OrderItem> res = new ArrayList<OrderItem>();
				
				while (rs.next()) {
					OrderItem item = new OrderItem();
					Product product = new Product();
					
					product.setCategory(rs.getString("products.category"));
					product.setDescription(rs.getString("products.description"));
					product.setId(rs.getString("products.id"));
					product.setImgurl(rs.getString("products.imgurl"));
					product.setName(rs.getString("products.name"));
					product.setPnum(rs.getInt("products.pnum"));
					product.setPrice(rs.getDouble("products.price"));
					
					item.setBuyNum(rs.getInt("orderitem.buynum"));
					item.setP(product);

					res.add(item);
				}
				
				return res;
			}
			
		}, order.getId());
	}

	@Override
	public boolean createOrderItem(Order order, Product product, int buynum) throws SQLException {
		String sql = "insert into orderitem(order_id, product_id,buynum) values(?,?,?)";
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		try {
			runner.update(sql, order.getId(), product.getId(), buynum);
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	
}
